//
//  XPOAuthViewController.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/11.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit
import SVProgressHUD

let appKey = "1072259284"
let appSecret = "7954bc7e998c57d77fde11d83f76f4af"
let redurectURL = "http://www.baidu.com"

class XPOAuthViewController: UIViewController {
    
    lazy var webView = UIWebView()
    
    override func loadView() {
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavUI()
        
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redurectURL)"
        
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        webView.loadRequest(request)
    }
}


// MARK: - UI搭建
extension XPOAuthViewController {
    private func setupNavUI() {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 16, target: self, action: #selector(XPOAuthViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 16, target: self, action: #selector(XPOAuthViewController.autoLoginAction))
    }
}


// MARK: - 点击事件
extension XPOAuthViewController {
    @objc private func cancelAction() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoLoginAction() {
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '1373814735@qq.com'; document.getElementById('passwd').value = 'ajdd1314'");
    }
}


// MARK: - UIWebViewDelegate
extension XPOAuthViewController: UIWebViewDelegate {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL?.absoluteString else {
            return false
        }
        
        if url.hasPrefix(redurectURL) == false {
            return true
        }

        if let query = request.URL?.query where query.hasPrefix("code=")  {
            let code = query.substringFromIndex("code=".endIndex)
            XPUserAccountViewModel.defaultUserAccount.userAccessToken(code, complete: { (isSucess) -> () in
                if isSucess {
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(loginSuccessNotification, object: self)
                    })
                }else {
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
            })
        }else{
            dismissViewControllerAnimated(true, completion: nil)
        }
        return false
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        SVProgressHUD.setDefaultMaskType(.Black)
    }
}

